const express = require('express');
const router = express.Router();
const { getToken } = require('../token/token');
const executeQuery = require('../MySQL/connect');

router.post('/', async (req, res) => {
  try {
    // 验证 token
    const tokenResult = getToken(req.headers.authorization);
    if (!tokenResult.boolean) {
      return res.status(405).send(tokenResult.msg);
    }
    // if(!tokenResult.isAdmin){
    //   return res.status(401).send('你不是管理员，无法查询');
    // }
    const currentPage = req.body.currentPage || 1;
    const pageSize = req.body.pageSize || 10;
    const startIndex = (currentPage - 1) * pageSize;
    const { find } = req.body;

    // 构建动态查询条件
    const conditions = [];
    if (find.name) conditions.push(`name LIKE '%${find.name}%'`);
    if (find.sex) conditions.push(`sex = '${find.sex}'`);
    if (find.age) conditions.push(`age = ${find.age}`);
    if (find.College) conditions.push(`College LIKE '%${find.College}%'`);
    if (find.class) conditions.push(`class LIKE '%${find.class}%'`);
    if (find.specialized) conditions.push(`specialized LIKE '%${find.specialized}%'`);

    let conditionClause = '';
    if (conditions.length > 0) {
      conditionClause = `WHERE ${conditions.join(' AND ')}`;
    }

    // 使用 Promise 化的连接池执行查询
    const sql = `SELECT * FROM STUDENTS ${conditionClause} LIMIT ${startIndex}, ${pageSize};`;
    const result = await executeQuery(sql);

    // 获取总记录数
    const totalCountSql = `SELECT COUNT(*) as totalCount FROM STUDENTS ${conditionClause};`;
    const countResult = await executeQuery(totalCountSql);
    const totalCount = countResult[0].totalCount;

    // 计算总页数
    const totalPages = Math.ceil(totalCount / pageSize);

    if (result.length === 0) {
      return res.status(404).send('抱歉！没有找到符合条件的学生');
    }

    return res.status(200).send({
      msg: `请求成功: 当前第${currentPage}页，一共${pageSize}条数据`,
      totalPages,
      currentPage,
      pageSize,
      students: result,
    });
  } catch (error) {
    console.error('数据库查询错误:', error);
    return res.status(500).send({ msg: '服务器内部错误' });
  }
});

module.exports = router;
